/*
 * JFrameCadUsuario.java
 *
 * Created on 23/06/2011, 15:03:56
 */
package br.unesp.demac.bcc.soo.clarus.view;

import br.unesp.demac.bcc.soo.clarus.bean.Aluno;
import br.unesp.demac.bcc.soo.clarus.bean.Login;
import br.unesp.demac.bcc.soo.clarus.dao.AlunoDAO;
import br.unesp.demac.bcc.soo.clarus.dao.AlunoDAOImp;
import br.unesp.demac.bcc.soo.clarus.util.FrameUtil;
import java.sql.SQLException;
import java.text.ParseException;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author Evaldo
 */
public class JFrameCadUsuario extends javax.swing.JFrame {

    /** Creates new form JFrameCadUsuario */
    public JFrameCadUsuario() {
        initComponents();
        
        FrameUtil.centralizar(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblCadastrarUsuarios = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        lblNomeUsuario = new javax.swing.JLabel();
        txtNomeUsuario = new javax.swing.JTextField();
        lblRa = new javax.swing.JLabel();
        lblSenha = new javax.swing.JLabel();
        lblConfirmeSenha = new javax.swing.JLabel();
        txtSenha = new javax.swing.JPasswordField();
        txtConfirmarSenha = new javax.swing.JPasswordField();
        btnLimpar = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        MaskFormatter mask = null;

        try{
            mask = new MaskFormatter("###.###.###");  
            mask.setPlaceholderCharacter('_');
        }
        catch(ParseException ex){
        }
        txtRa = txtRa = new JFormattedTextField(mask);
        lblLogin = new javax.swing.JLabel();
        txtLogin = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Usuários");
        setResizable(false);

        lblCadastrarUsuarios.setFont(new java.awt.Font("Calibri", 1, 18));
        lblCadastrarUsuarios.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unesp/demac/bcc/soo/clarus/imagens/icon_usuario.png"))); // NOI18N
        lblCadastrarUsuarios.setText("Cadastrar Usuários");

        lblNomeUsuario.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblNomeUsuario.setText("Nome do Usuário:");

        lblRa.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblRa.setText("RA:");

        lblSenha.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblSenha.setText("Senha:");

        lblConfirmeSenha.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblConfirmeSenha.setText("Confirme a senha:");

        btnLimpar.setText("Limpar");
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        lblLogin.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblLogin.setText("Login de Usuário:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
                    .addComponent(lblCadastrarUsuarios)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblNomeUsuario)
                            .addComponent(lblLogin)
                            .addComponent(lblRa)
                            .addComponent(lblSenha))
                        .addGap(19, 19, 19)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtRa, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                            .addComponent(txtNomeUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 276, Short.MAX_VALUE)
                            .addComponent(txtLogin)
                            .addComponent(txtSenha, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(193, 193, 193)
                        .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblConfirmeSenha)
                        .addGap(18, 18, 18)
                        .addComponent(txtConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCadastrarUsuarios)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNomeUsuario)
                    .addComponent(txtNomeUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLogin)
                    .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblRa))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblSenha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblConfirmeSenha))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalvar)
                    .addComponent(btnLimpar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        if (validarItensTela()){
            
            boolean statusInsercao = false;
            //Usuario usu = new Usuario();
            //usu.setNome(txtNomeUsuario.getText().trim());
            
            Aluno alun = new Aluno();
            String ra = txtRa.getText().trim().replace(".", "");
            alun.setRa(Long.parseLong(ra));
            alun.setNome(txtNomeUsuario.getText().trim());
            
            Login login = new Login();
            login.setLoginUsuario(txtLogin.getText().trim());
            login.setSenhaUsuario(txtSenha.getText());            
            alun.setLogin(login);
                        
            try{
                //UsuarioDAOImp usuDao = new UsuarioDAOImp();
                //statusInsercao = usuDao.salvarUsuario(usu, alun);
                AlunoDAO adao = new AlunoDAOImp();
                statusInsercao = adao.salvarAluno(alun);
            }
            catch(SQLException ex){
                System.out.println("Erro na inserção." + ex.getMessage());
            }
                        
            if (statusInsercao){
                limparControles();
                JOptionPane.showMessageDialog(this, "Usuário inserido com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);                
            }
            else
                JOptionPane.showMessageDialog(this, "Problemas ao inserir usuário.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
        limparControles();
    }//GEN-LAST:event_btnLimparActionPerformed

    /**
     * Verifica se todos itens obrigatórios da tela foram preenchidos
     * @return Status da validaçao
     */
    private boolean validarItensTela(){
        
        if (txtNomeUsuario.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Preencha o campo nome do usuário.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (txtLogin.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Preencha o campo login.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }        
        else if (txtRa.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Preencha o campo RA.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }       
        else if (txtSenha.getPassword().length == 0){
            JOptionPane.showMessageDialog(this, "Preencha o campo senha.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }  
        else if (txtConfirmarSenha.getPassword().length == 0){
            JOptionPane.showMessageDialog(this, "Confirme a senha.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (! txtSenha.getText().equals(txtConfirmarSenha.getText())){
            JOptionPane.showMessageDialog(this, "Senhas não conferem.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
                return true;
    }
    
    /**
     * Limpa os controles da tela
     */
    private void limparControles(){
        txtNomeUsuario.setText(null);
        txtLogin.setText(null);
        txtRa.setText(null);
        txtSenha.setText(null);
        txtConfirmarSenha.setText(null);
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new JFrameCadUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblCadastrarUsuarios;
    private javax.swing.JLabel lblConfirmeSenha;
    private javax.swing.JLabel lblLogin;
    private javax.swing.JLabel lblNomeUsuario;
    private javax.swing.JLabel lblRa;
    private javax.swing.JLabel lblSenha;
    private javax.swing.JPasswordField txtConfirmarSenha;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNomeUsuario;
    private javax.swing.JFormattedTextField txtRa;
    private javax.swing.JPasswordField txtSenha;
    // End of variables declaration//GEN-END:variables
}
